package com.mingyuan.library.provider.common.aop;


import com.mingyuan.library.domain.common.enums.CommonExceptionCodeEnum;
import com.mingyuan.library.domain.common.exception.BusinessException;
import com.mingyuan.library.provider.common.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author yangzhongkun
 * @version V1.0
 * @description: 异常处理
 * @AnnotationName: RpcResult
 * @date 2021/7/22 10:40
 **/
@Slf4j
@Order(0)
@Aspect
@Component
public class GlobalExceptionAspectHandler {

    /**
     * 声明自定义@RestResponse注解为切点
     * @author yangzk
     * @date 2024/1/5 19:56
     **/
    @Pointcut("@annotation(com.mingyuan.library.infra.common.anntation.RestResponse)")
    public void restResult() {
    }


    /**
     * 异常处理切面 将异常包装为Result
     * @author yangzk
     * @param proceedingJoinPoint 切入点
     * @date 2024/1/5 19:56
     **/
    @Around("restResult()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) {
        try {
            long startTime = System.currentTimeMillis();
            log.info("接口调用开始class:{}",proceedingJoinPoint.getThis());
            Object proceed = proceedingJoinPoint.proceed();
            log.info("接口调用完成class:{},耗时:{}ms",proceedingJoinPoint.getThis(),(System.currentTimeMillis()-startTime));
            return proceed;
        }  catch (BusinessException e) {
            log.info("全局RPC逻辑处理异常捕捉：", e);
            return Result.fail(e.getErrCode(), e.getMessage());
        } catch (InterruptedException e){
            log.error("系统错误,全局RPC逻辑处理InterruptedException捕获error",e);
            return Result.fail(CommonExceptionCodeEnum.THREAD_INTERRUPTED.getErrCode(),e.getMessage());
        }catch (Exception e) {
            log.error("系统错误,全局逻辑处理异常捕捉error:", e);
            return Result.fail(CommonExceptionCodeEnum.DEFAULT_ERROR.getErrCode(), e.getMessage());
        } catch (Throwable e) {
            log.error("未知错误，全局逻辑处理异常捕捉：", e);
            return Result.fail(CommonExceptionCodeEnum.UNKNOWN.getErrCode(), e.getMessage());
        }
    }
}
